package com.lsy.weizhi2.fragment;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Fragment;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.annotation.Nullable;
import android.text.InputType;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.lsy.weizhi2.JsonObject.LoginObject;
import com.lsy.weizhi2.R;
import com.lsy.weizhi2.activity.HomePage;
import com.lsy.weizhi2.config.Constants;
import com.lsy.weizhi2.config.MyInfo;
import com.lsy.weizhi2.myutils.FragmentCall;
import com.lsy.weizhi2.utils.MyMethod;
import com.lsy.weizhi2.utils.MyOkHttpUtils;
import com.lsy.weizhi2.utils.RegexUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;


/**
 * Created by 嗨哟 on 2016/12/6.
 */
public class RegisterFragment extends Fragment implements View.OnClickListener, View.OnFocusChangeListener {
    private View view, register_phone_line, register_code_line, register_password_line, register_invite_line;
    private Context context;
    private EditText register_phone_et, register_code_et, register_password_et, register_invite_et;
    private TextView register_code_tv;
    private ImageView register_show_password_iv;
    private ImageView register_phone_iv, register_code_iv, register_password_iv, register_invite_iv;
    private Button register_btn;
    private boolean ispwshow, isrepwshow;
    private boolean check;
    private FragmentCall fragmentCall;
    private Gson gson;
    private CountDownTimer timer = new CountDownTimer(60000, 1000) {
        @Override
        public void onTick(long l) {
            register_code_tv.setText(l / 1000 + "秒后重发");
        }

        @Override
        public void onFinish() {
            register_code_tv.setEnabled(true);
            register_code_tv.setClickable(true);
            register_code_tv.setText("获取验证码");
            register_code_tv.setTextColor(context.getResources().getColor(R.color.clicked_ok));
        }
    };

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_register, container, false);
        register_phone_et = (EditText) view.findViewById(R.id.register_phone_et);
        register_phone_et.setOnFocusChangeListener(this);
        register_code_et = (EditText) view.findViewById(R.id.register_code_et);
        register_code_et.setOnFocusChangeListener(this);
        register_password_et = (EditText) view.findViewById(R.id.register_password_et);
        register_password_et.setOnFocusChangeListener(this);
        register_invite_et = (EditText) view.findViewById(R.id.register_invite_et);
        register_invite_et.setOnFocusChangeListener(this);
        register_code_tv = (TextView) view.findViewById(R.id.register_code_tv);
        register_show_password_iv = (ImageView) view.findViewById(R.id.register_show_password_iv);
        register_phone_line = view.findViewById(R.id.register_phone_line);
        register_code_line = view.findViewById(R.id.register_code_line);
        register_password_line = view.findViewById(R.id.register_password_line);
        register_invite_line = view.findViewById(R.id.register_invite_line);
        register_invite_iv = (ImageView) view.findViewById(R.id.register_invite_iv);
        register_btn = (Button) view.findViewById(R.id.register_btn);
        register_btn.setOnClickListener(this);
        register_code_tv.setOnClickListener(this);
        register_show_password_iv.setOnClickListener(this);
        register_phone_iv = (ImageView) view.findViewById(R.id.register_phone_iv);
        register_code_iv = (ImageView) view.findViewById(R.id.register_code_iv);
        register_password_iv = (ImageView) view.findViewById(R.id.register_password_iv);
        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        context = getActivity();
        fragmentCall = (FragmentCall) getActivity();
        gson=new Gson();
    }

    public void setCheck(boolean check) {
        this.check = check;
    }

    @Override
    public void onClick(View view) {
        String user_phone = register_phone_et.getText().toString();
        switch (view.getId()) {
            case R.id.register_show_password_iv:
                if (ispwshow) {
                    register_password_et.setTransformationMethod(PasswordTransformationMethod.getInstance());
                    register_show_password_iv.setImageResource(R.mipmap.login_ico1_10);
                    ispwshow = false;
                } else {
                    register_password_et.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                    register_show_password_iv.setImageResource(R.mipmap.login_ico2_10);
                    ispwshow = true;
                }
                break;
            case R.id.register_code_tv:
                if (RegexUtils.checkMobile(user_phone)) {
                    Getcode(user_phone);
                } else {
                    MyMethod.showToast(context, "请输入正确手机号码");
                }
                break;
            case R.id.register_btn:
                //MyMethod.toJumpActivity(context,Select_HeadImg.class);//测试用直接跳转头像上传
                if (check) {
                    String password = register_password_et.getText().toString();
                    String invite = register_invite_et.getText().toString();
                    // String re_password=register_repassword_et.getText().toString();
                    String code = register_code_et.getText().toString();
                    Register(user_phone, password, code, invite);
                } else {
                    MyMethod.ShowDialog(context,"请阅读协议后点击同意");
                }
                break;
        }
    }

    private void Getcode(String phone) {
        MyOkHttpUtils.getInstance(context).doPostSMS(Constants.SEND_SMS + phone, null)
                .excute(new MyOkHttpUtils.OKCallBack() {
                    @Override
                    public void onFailure(String message) {
                            Log.i("Register","message======="+message);
                    }

                    @Override
                    public void onResponse(String message) {
                        if (message != null) {
                            try {
                                JSONObject jsonObject = new JSONObject(message);
                                boolean result = jsonObject.getBoolean("result");
                                if (result) {
                                    timer.start();
                                }else{
                                    MyMethod.ShowDialog(context,"系统故障");
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }

                        }
                    }
                });
    }

    private void Register(final String name, final String password, final String code, String invite) {
        Map<String, String> map = new HashMap<>();
        map.put("username", name);
        map.put("password", password);
        map.put("smsCode", code);
        if(invite!=null&&invite.length()!=0){
            map.put("introducer",invite);
        }
        MyOkHttpUtils.getInstance(context).doPost(Constants.USER_REGISTER, map)
                .excute(new MyOkHttpUtils.OKCallBack() {
                    @Override
                    public void onFailure(String message) {

                    }

                    @Override
                    public void onResponse(String message) {
                        Log.i("RegisterFragment","message=register="+message);
                        if (message != null) {
                            try {
                                JSONObject jsonObject = new JSONObject(message);
                                boolean result = jsonObject.getBoolean("result");
                                if (result) {
                                    new AlertDialog.Builder(context).setMessage("请选择操作")
                                            .setNegativeButton("直接登录", new DialogInterface.OnClickListener() {
                                                @Override
                                                public void onClick(DialogInterface dialog, int which) {
                                                    LoginAccount(name,password);
                                                    dialog.dismiss();
                                                }
                                            })
                                            .setNeutralButton("返回登录", new DialogInterface.OnClickListener() {
                                                @Override
                                                public void onClick(DialogInterface dialog, int which) {
                                                    fragmentCall.Select(0);
                                                    dialog.dismiss();
                                                }
                                            })
                                            .setPositiveButton("取消", new DialogInterface.OnClickListener() {
                                                @Override
                                                public void onClick(DialogInterface dialog, int which) {
                                                    dialog.dismiss();
                                                }
                                            }).show();

                                } else {
                                    MyMethod.ShowDialog(context, jsonObject.getString("message"));
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }

                        }
                    }
                });
    }

    private void AllClearFocus() {
        register_phone_iv.setImageResource(R.mipmap.login_ico2_03);
        register_code_iv.setImageResource(R.mipmap.login_ico1_06);
        register_invite_iv.setImageResource(R.mipmap.login_ico1_06);
        register_password_iv.setImageResource(R.mipmap.login_ico2_08);
        register_phone_line.setBackgroundResource(R.color.clicked_no);
        register_code_line.setBackgroundResource(R.color.clicked_no);
        register_password_line.setBackgroundResource(R.color.clicked_no);
        register_invite_line.setBackgroundResource(R.color.clicked_no);
    }

    private void PhoneHasFocus() {
        register_phone_iv.setImageResource(R.mipmap.login_ico1_03);
        register_phone_line.setBackgroundResource(R.color.clicked_ok);
    }

    private void CodeHasFocus() {
        register_code_iv.setImageResource(R.mipmap.login_ico2_06);
        register_code_line.setBackgroundResource(R.color.clicked_ok);
    }

    private void PWHasFocus() {
        register_password_iv.setImageResource(R.mipmap.login_ico1_08);
        register_password_line.setBackgroundResource(R.color.clicked_ok);
    }

    private void inviteHasFocus() {
        register_invite_iv.setImageResource(R.mipmap.login_ico2_06);
        register_invite_line.setBackgroundResource(R.color.clicked_ok);
    }

    @Override
    public void onFocusChange(View view, boolean b) {
        if (b) {
            switch (view.getId()) {
                case R.id.register_phone_et:
                    AllClearFocus();
                    PhoneHasFocus();
                    break;
                case R.id.register_code_et:
                    AllClearFocus();
                    CodeHasFocus();
                    break;
                case R.id.register_password_et:
                    AllClearFocus();
                    PWHasFocus();
                    break;
                case R.id.register_invite_et:
                    AllClearFocus();
                    inviteHasFocus();
                    break;
            }
        }
    }

    private void LoginAccount(String username,String password){
        Map<String,String> map=new HashMap<>();
        map.put("username",username);
        map.put("password",password);
        MyOkHttpUtils.getInstance(context).doPostLogin(Constants.USER_LOGIN,map)
                .excute(new MyOkHttpUtils.OKCallBack() {
                    @Override
                    public void onFailure(String message) {

                    }

                    @Override
                    public void onResponse(String message) {
                        Log.i("RegisterFragment","message=s=="+message);
                        if(message!=null){
                            try {
                                JSONObject jsonobject=new JSONObject(message);
                                boolean isSuccess=jsonobject.getBoolean("result");
                                if(isSuccess){
                                    //登录成功--暂时保存在对象中
                                    LoginObject loginObject = gson.fromJson(message,LoginObject.class);
                                    String token=loginObject.getMessage();
                                    MyInfo.Token=token;
                                    MyInfo.User_Id=loginObject.getData().getId();
                                    MyInfo.Name=loginObject.getData().getUsername();
                                    //保存部分用户信息到本地
                                    SharedPreferences sharedPreferences=context.getSharedPreferences(MyInfo.User_info,0);
                                    SharedPreferences.Editor editor=sharedPreferences.edit();
                                    editor.putInt("user_id",loginObject.getData().getId());
                                    // editor.putString("head_image",Constants.SERVICE_IP+loginAccept.getMessage().getAvatar());
                                    editor.putString("name",loginObject.getData().getUsername());
                                    editor.putString("phone",loginObject.getData().getPhone());
                                    editor.putString("token",token);
                                    editor.commit();
                                    MyMethod.toActivity(context, HomePage.class);
                                    ((Activity)context).finish();
                                }else{
                                    MyMethod.ShowDialog(context,jsonobject.getString("message"));
                                }
                            } catch (JSONException e) {
                                MyMethod.showToast(context,message);
                            }
                        }
                    }
                });
    }
}
